<!--产品标准产能：编辑-->
<template>
  <div>
    <el-dialog
      top="5vh"
      width="85%"
      append-to-body
      custom-class="productStandardCapacityEditDialog"
      :title="editDialog.title"
      v-if="showEditDialog"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="showEditDialog"
      @close="handleEditReset"
    >
      <div class="editArea" v-loading="editDialog.loading">
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text">产品信息</div>
        </div>
        <avue-form ref="editRef" v-model="editDialog.form" :option="editDialog.option" @submit="handleEditSubmit" @reset-change="handleEditReset"> </avue-form>
        <div class="dispatch-title">
          <div class="dispatch-title-dot"></div>
          <div class="dispatch-title-text">产能设置</div>
        </div>
        <avue-crud
          ref="editCrud"
          v-model="editDialog.tableForm"
          :option="editDialog.tableOption"
          :data="editDialog.tableData"
          @row-save="handleEditSave"
          @row-update="handleEditUpdate"
          @selection-change="selectionEditChange"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleEditAdd">新 增</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="handleEditDel">删 除</el-button>
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button type="text" size="small" :icon="scope.row.$cellEdit ? 'el-icon-plus' : 'el-icon-edit'" @click="handleRowCell(scope.row, scope.index)">
              {{ scope.row.$cellEdit ? '保存' : '编辑' }}
            </el-button>
            <el-button v-if="scope.row.$cellEdit" type="text" size="small" icon="el-icon-cancel" @click="handleRowCancel(scope.row, scope.index)">取消</el-button>
            <el-button v-else type="text" size="small" icon="el-icon-delete" @click="handleEditRowDel(scope.row, scope.index)">删除</el-button>
          </template>
          <template slot="uphHeader" slot-scope="{ column }">
            <el-tooltip class="item" effect="dark" placement="top-start">
              <i class="el-icon-info" style="color: #606266"></i>
              <div slot="content">UPH（units per hour）指该工段下产线生产该产品的单位小时产能，即每小时的产量</div>
            </el-tooltip>
            <span>&nbsp;{{ column.label }}</span>
          </template>
          <template slot-scope="{ row }" slot="uph">
            <span v-if="!row.$cellEdit">{{ row.uph }}</span>
            <avue-input-number v-else size="mini" v-model="row.uph" :minRows="0" :disabled="!row.$cellEdit"></avue-input-number>
          </template>
          <template slot-scope="{ row }" slot="openLineDuration">
            <span v-if="!row.$cellEdit">{{ row.openLineDuration }}</span>
            <avue-input-number v-else size="mini" v-model="row.openLineDuration" :minRows="0" :disabled="!row.$cellEdit"></avue-input-number>
          </template>
          <template slot-scope="{ row }" slot="clearLineDuration">
            <span v-if="!row.$cellEdit">{{ row.clearLineDuration }}</span>
            <avue-input-number v-else size="mini" v-model="row.clearLineDuration" :minRows="0" :disabled="!row.$cellEdit"></avue-input-number>
          </template>
          <template slot-scope="{ row, index }" slot="lineId">
            <span v-if="!row.$cellEdit">{{ row.lineName }}</span>
            <el-select
              v-else
              size="mini"
              v-model="row.lineId"
              :disabled="!row.$cellEdit"
              @visible-change="(status) => handleLineVisibleChange(status, row, index)"
              @change="(value) => handeLineChange(value, row, index)"
            >
              <el-option v-for="item in row.lineList" :key="item.lineId" :label="item.lineName" :value="item.lineId"> </el-option>
            </el-select>
          </template>
          <template slot-scope="{ row, index }" slot="sectionId">
            <span v-if="!row.$cellEdit">{{ row.sectionName }}</span>
            <el-cascader
              v-else
              size="mini"
              :show-all-levels="false"
              v-model="row.sectionId"
              :options="sectionList"
              :disabled="!row.$cellEdit"
              @change="(value) => handleSectionChange(value, index)"
            ></el-cascader>
          </template>
        </avue-crud>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-delete" @click="handleFooterEditReset">取消</el-button>
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleFooterEditSubmit">保存</el-button>
      </span>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </div>
</template>

<script>
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { capacitySubmit, capacityCheck } from '@/api/product/productStandardCapacity';
export default {
  components: {
    GlobalModalTemplate
  },
  props: {
    showEditDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rowId: null,
      sectionList: [], // 工段列表
      editDialog: {
        title: '编辑',
        form: {},
        loading: false,
        option: {
          searchShow: true,
          searchMenuSpan: 6,
          menuPosition: 'right',
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 100,
          column: [
            {
              label: '产品编码',
              prop: 'productPartNo',
              disabled: true,
              type: 'search',
              span: 12,
              appendClick: () => {
                this.openUserCommonModal({ type: 'productCode' });
              },
              rules: [
                {
                  required: true,
                  message: '请选择产品编码',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '产品名称',
              prop: 'productPartName',
              disabled: true,
              span: 12
            },
            {
              label: '产品型号',
              prop: 'productPartModel',
              disabled: true,
              span: 12
            },
            {
              label: '产品类型',
              prop: 'productPartType',
              search: true,
              type: 'select',
              disabled: true,
              span: 12,
              dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
              props: {
                label: 'dictValue',
                value: 'dictKey'
              }
            }
          ]
        },
        tableOption: {
          height: '250px',
          // maxHeight: '250px',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          border: true,
          index: true,
          indexLabel: '序号',
          viewBtn: false,
          editBtn: false,
          addBtn: false,
          page: false,
          delBtn: false,
          cellBtn: false,
          cancelBtn: false,
          labelWidth: 130,
          selection: true,
          refreshBtn: false,
          columnBtn: false,
          highlightCurrentRow: true, // 选中高亮
          dialogClickModal: false,
          menuWidth: 200,
          column: [
            {
              label: '工段名称',
              prop: 'sectionId',
              rules: [
                {
                  required: true,
                  message: '请选择工段名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '产线名称',
              prop: 'lineId',
              rules: [
                {
                  required: true,
                  message: '请选择产线名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: 'UPH',
              width: 150,
              prop: 'uph',
              type: 'number',
              cell: true,
              minRows: 0,
              rules: [
                {
                  required: true,
                  message: '请输入UPH',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '开线时长（分）',
              prop: 'openLineDuration',
              type: 'number',
              cell: true,
              minRows: 0,
              precision: 0,
              rules: [
                {
                  required: true,
                  message: '请输入开线时长（分）',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '清线时长（分）',
              prop: 'clearLineDuration',
              type: 'number',
              cell: true,
              minRows: 0,
              precision: 0,
              rules: [
                {
                  required: true,
                  message: '请输入清线时长（分）',
                  trigger: 'blur'
                }
              ]
            }
          ]
        },
        rowIndex: -1,
        selectionList: [],
        tableData: [],
        tableForm: {},
        tablePage: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        }
      },
      form: {},
      query: {},
      cloneForm: {},
      loading: true,
      selectionList: [],
      data: [],
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    // 获取工段级联列表
    getWorkSection(sectionList) {
      const that = this;
      that.editDialog.loading = true;
      that.sectionList = sectionList;
      setTimeout(() => {
        that.editDialog.loading = false;
      }, 200);
    },
    // 获取产线列表
    handleSectionChange(value, index) {
      const that = this;
      console.log('value', value);
      if (value.length == 1) {
        let sFind = that.sectionList.find((item) => item.value == value[0]);
        that.editDialog.tableData[index].sectionCode = sFind.code;
        that.editDialog.tableData[index].sectionName = sFind.label;
        that.editDialog.tableData[index].lineList = sFind.lineList;
      } else if (value.length == 2) {
        let sFind = that.sectionList.find((item) => item.value == value[0]);
        console.log(sFind, 'sFind');
        if (sFind) {
          that.editDialog.tableData[index].sectionCode = sFind.children.find((cc) => cc.value == value[1]).code;
          that.editDialog.tableData[index].sectionName = sFind.children.find((cc) => cc.value == value[1]).label;
          that.editDialog.tableData[index].lineList = sFind.children.find((cc) => cc.value == value[1]).lineList;
        }
      }
      // that.$set(that.editDialog.tableData[index], 'lineList', []);
      that.$set(that.editDialog.tableData[index], 'lineId', '');
      that.$set(that.editDialog.tableData[index], 'lineCode', '');
      that.$set(that.editDialog.tableData[index], 'lineName', '');
    },
    handleLineVisibleChange(status, row, index) {
      const that = this;
      if (status && row.sectionId) {
        let sectionId = Array.isArray(row.sectionId) ? row.sectionId[0] : row.sectionId;
        console.log(sectionId, that.sectionList, 'that.sectionList');
        // getLineListBySection(sectionId)
        //   .then((res) => {
        //     let data = res.data.data;
        //     let lineList = data.bindingLines.map((d) => {
        //       return {
        //         value: d.id,
        //         label: d.name,
        //         code: d.code
        //       };
        //     });
        //     that.$set(that.editDialog.tableData[index], 'lineList', lineList);
        //   })
        //   .catch((err) => {});
      }
    },
    handeLineChange(value, row, index) {
      let lineFind = row.lineList.find((lItem) => lItem.lineId == value);
      this.editDialog.tableData[index].lineCode = lineFind.lineCode;
      this.editDialog.tableData[index].lineName = lineFind.lineName;
    },
    handleEdit(row, index) {
      this.showEditDialog = true;
    },
    openUserCommonModal(params) {
      this.visibile = true;
      this.modalName = 'partmasterModal';
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 90,
        method: 'post',
        url: '/api/mes-admin/part-master/page',
        method: 'get',
        isPage: true,
        templateName: 'NOWORKPARTMASTER'
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partmasterModal':
          this.editDialog.form.productPartNo = this._get(rowData, 'partNo', '');
          this.editDialog.form.productPartName = this._get(rowData, 'name', '');
          this.editDialog.form.productPartModel = this._get(rowData, 'partModel', '');
          this.editDialog.form.productPartType = this._get(rowData, 'partType', '');
          this.editDialog.form.productPartId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    handleEditSave(form, done) {
      done();
    },
    handleEditUpdate(form, index, done, loading) {
      loading();
      done();
    },
    handleEditAdd() {
      this.editDialog.tableData.push({
        sectionId: '',
        sectionCode: '',
        sectionName: '',
        lineId: '',
        lineCode: '',
        lineName: '',
        lineList: [],
        uph: undefined,
        openLineDuration: undefined,
        clearLineDuration: undefined,
        $cellEdit: true
      });
      let tableRef = this.$refs.editCrud;
      let bodyWrapper = tableRef.$el.querySelector('.el-table__body-wrapper');
      if (this.editDialog.tableData.length > 5) {
        this.$nextTick(() => {
          let tr = bodyWrapper.querySelectorAll('tr')[this.editDialog.tableData.length - 1];
          if (!bodyWrapper || !tr) {
            return;
          }
          bodyWrapper.scrollTop = tr.offsetTop;
          bodyWrapper.style.scrollBehavior = 'smooth';
        });
      }
    },
    handleEditDel() {
      if (this.editDialog.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editDialog.tableData = this.editDialog.tableData.filter((d) => !this.editDialog.selectionList.map((list) => list.$index).includes(d.$index));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    },
    handleRowCell(row, index) {
      this.$refs.editCrud.rowCell(row, index);
      let sectionList = flatSectionList(this.sectionList);
      let find = sectionList.find((item) => item.value == row.sectionId);
      if (find) {
        row.lineList = find.lineList;
      }
      function flatSectionList(list) {
        let data = [];
        list.forEach((item) => {
          data.push(item);
          if (item.children && item.children.length > 0) {
            item.children.forEach((child) => {
              data.push(child);
            });
          }
        });
        return data;
      }
    },
    handleRowCancel(row, index) {
      this.$refs.editCrud.rowCancel(row, index);
    },
    handleEditRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editDialog.tableData.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    },
    selectionEditChange(list) {
      this.editDialog.selectionList = list;
    },
    // 编辑保存
    handleFooterEditSubmit() {
      this.$refs.editRef.submit();
    },
    // 编辑取消
    handleFooterEditReset() {
      this.$refs.editRef.resetForm();
    },
    hasDuplicates(arr) {
      return new Set(arr).size !== arr.length;
    },
    async handleEditSubmit(form, done) {
      if (this.editDialog.tableData.length == 0) {
        this.$message.warning('产能设置数据不能为空');
        return false;
      }
      let isEmptyData = this.editDialog.tableData.every((item) => {
        return item.sectionId && item.lineId;
      });
      if (!isEmptyData) {
        this.$message.warning('产能设置数据中工段名称和产线名称不能为空，请仔细检查');
        return;
      }
      form.standardCapacityDetailList = this.editDialog.tableData.map((item) => {
        return {
          clearLineDuration: item.clearLineDuration,
          openLineDuration: item.openLineDuration,
          sectionId: Array.isArray(item.sectionId) ? item.sectionId[item.sectionId.length - 1] : item.sectionId,
          sectionCode: item.sectionCode,
          sectionName: item.sectionName,
          lineId: item.lineId,
          lineCode: item.lineCode,
          lineName: item.lineName,
          uph: item.uph
        };
      });
      console.log('form', form);
      // 检查form.standardCapacityDetailList中是否有重复的工段产线
      let sectionIdAndlineIds = form.standardCapacityDetailList.map((item) => item.sectionId + item.lineId);
      let setSectionIdAndlineIds = [...new Set(sectionIdAndlineIds)];
      if (sectionIdAndlineIds.length > setSectionIdAndlineIds.length) {
        // 找到重复工段产线名称
        let repeatLineNames = form.standardCapacityDetailList
          .filter((item, index, arr) => {
            return arr.findIndex((i) => i.sectionId + i.lineId === item.sectionId + item.lineId) !== index;
          })
          .map((item) => item.sectionName + item.lineName)
          .join(',');
        this.$message.warning(`${repeatLineNames}有多条，同一工段产线只能选一次，请勿重复操作，请将重复产线删除！`);
        return;
      }
      this.handleCapacity(form, done);
    },
    async submitCapacity(form) {
      try {
        await capacitySubmit(form);
      } catch (error) {
        console.error('提交产能时发生错误', error);
      }
    },
    async handleCapacity(form, done) {
      try {
        const res = await capacityCheck(form);
        const data = res.data.data;
        if (data !== 'true') {
          // 弹出确认对话框
          const confirmResult = await this.$confirm(data, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
          if (confirmResult) {
            // 用户点击确认，继续提交
            await this.submitCapacity(form);
          }
        } else {
          // 已绑定所有产线,直接提交
          await this.submitCapacity(form);
        }
        // 关闭对话框并通知父组件
        this.showEditDialog = false;
        this.$emit('closeEditDialog');
        done();
      } catch (error) {
        console.error('处理产能时发生错误', error);
        done();
      }
    },
    handleEditReset() {
      this.showEditDialog = false;
      this.editDialog.form = {};
      this.editDialog.tableData = [];
      this.$emit('closeEditDialog');
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .productStandardCapacityEditDialog {
  .el-dialog__body {
    padding: 0 20px;
  }
  .avue-form__menu--right {
    display: none;
  }
  .dispatch-title {
    display: flex;
    align-items: center;
    margin: 20px 0;
    &-dot {
      background-color: rgb(102, 177, 255);
      width: 10px;
      height: 20px;
      margin-right: 8px;
    }
    &-text {
      font-weight: bold;
      font-size: 16px;
    }
  }
  .detailTitle {
    font-size: 16px;
    font-weight: bold;
    height: 50px;
    line-height: 50px;
    color: rgba(0, 0, 0, 0.85);
    border-bottom: 1px solid #eee;
  }
  .detailArea {
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
